package control

import (
	"strconv"
	//"asystem/config"
	"asystem/db"
	"asystem/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	//"strconv"
	//"time"
)

const (
	POST   = "POST"
	PUT    = "PUT"
	GET    = "GET"
	DELETE = "DELETE"
	//ADMINSESSIONKEY = "adminUser"
)

func loginHandler(c *gin.Context) {
	if c.Request.Method == POST {
		var uid, userName = "_", ""
		var tid int
		account := c.PostForm("name")
		if account == "" {
			c.JSON(200, gin.H{"errMsg": fmt.Sprintf("用户名不允许为空")})
			return
		}
		pwd := c.PostForm("passwd")
		if pwd == "" {
			c.JSON(200, gin.H{"errMsg": fmt.Sprintf("密码不允许为空！")})
			return
		}
		//learnMe := c.PostForm("learnMe")
		hasPwd := utils.HasPasswd(pwd)
		// 1. 根据用户名和密码去数据库查询，如果为空则表示不成功
		userData, err := db.UserSignCheckData(&db.Users{Account: account, Passwd: hasPwd})
		for _, v := range userData {
			uid = uid + strconv.Itoa(v.Uid)
			userName = v.UserName
			tid = v.TId
		}
		if err != nil || userName == "" {
			c.JSON(200, gin.H{"errMsg": fmt.Sprintf("登录失败，用户名或密码不正确")})
			return
		}
		users := &utils.UsersJsonData{
			UserName: userName,
			Tid:      tid,
		}
		usersByte, err := utils.JsonMarshal(users)
		if err != nil {
			c.JSON(200, gin.H{"errMsg": fmt.Sprintf("%v", err)})
			return
		}
		se := utils.InitSession(c, "admin")
		if err = se.SetSession(se.SesKey.SerSessKey, usersByte); err != nil {
			c.JSON(200, gin.H{"success": "", "errMsg": fmt.Sprintf("登录失败，后台缓存服务其错误，给您带来不便敬请谅解，错误代码：%v", err)})
			return
		}
		c.JSON(200, gin.H{"success": "success", "errMsg": ""})
		return
	}
	c.HTML(200, "template/login.html", gin.H{"title": "链力电子"})
}

func logOutHandler(c *gin.Context) {
	se := utils.InitSession(c, "admin")
	se.DelSession(se.SesKey.SerSessKey)
	c.JSON(200, gin.H{"success": "success", "errMsg": ""})
}
